package org.springframework.ai.mcp.sample.server;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ai.mcp.sample.enums.StatusUrl;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;

@Service
public class SystemService {


    private final RestClient restClient;
    private final ObjectMapper objectMapper;

    public SystemService() {
        this.restClient = RestClient.create();
        this.objectMapper = new ObjectMapper();
    }

    @Tool(description = "后端系统运行状态确认")
    public String systemStatus() {
        StringBuilder request = new StringBuilder("系统运行状态\n");
        for (StatusUrl statusUrl : StatusUrl.values()) {
            String url = statusUrl.getUrl();
            try {
                String jsonResponse = restClient.get().uri(url).retrieve().body(String.class);

                JsonNode jsonNode = objectMapper.readTree(jsonResponse);
                String status = jsonNode.get("status").asText();
                request.append(statusUrl.getReadme()).append(": ").append(status);
            } catch (Exception e) {
                return "服务器异常，请求url：" + url;
            }
        }
        return request.toString();
    }


    /**
     * 获取系统日志
     *
     * @param name 系统名称 例如 "CNC", "Remind", "消息推送系统"
     * @return 系统日志
     */

    @Tool(description = "获取系统日志")
    public String getLogUrl(String name) {
        return switch (name) {
            case "CNC", "cnc" -> restClient.get().uri(StatusUrl.CNC.getLogUrl()).retrieve().body(String.class);
            case "remind" -> restClient.get().uri(StatusUrl.Remind.getLogUrl()).retrieve().body(String.class);
            default -> "";
        };
    }
}
